<?php

namespace app\api\controller;

use app\api\model\Coupons;
use app\api\model\Orders;
use app\api\model\OrderVip;
use app\api\model\RechargeOrder;
use app\api\model\Recharges;
use app\api\model\UserBalanceLog;
use app\api\model\UserCoupons;
use app\api\model\UserGrade;
use app\api\model\Users;
use app\api\model\UserVip;
use app\api\model\Wechat;
use app\common\controller\Api;
use think\Controller;
use think\Db;
use think\Log;
use think\Request;
use Yansongda\Pay\Exceptions\GatewayException;

class Recharge extends Api
{
    protected $noNeedLogin = ['paymentResult'];
    protected $noNeedRight = ['*'];
    /**
     * 会员充值
     */
    public function pay($recharge_id, Wechat $wechat)
    {
        $recharge = Recharges::find($recharge_id);
        if (!$recharge) {
            $this->error('充值套餐不存在');
        }
        $user = Users::find($this->auth->getUserId());
        if (!$user) {
            $this->error('用户不存在');
        }
        $order_no = 'R'.date('YmdHis').mt_rand(100, 999);
        $data = [
            'order_no' => $order_no,
            'user_id' => $user->id,
            'recharge_id' => $recharge_id,
            'total_amount' => $recharge->recharge_money,
            'present_amount' => $recharge->present_money,
            'present_coupon_id' => $recharge->coupon_id,
            'createtime' => time(),
            'updatetime' => time()
        ];
        $order = RechargeOrder::create($data);
        if (!$order) {
            $this->error('创建订单失败，请联系管理员');
        }
        //微信支付
        try {
            $res = $wechat->miniapp($order, $user->openid, config('wechat.notify_url_vip'));
        } catch (\Exception $e) {
            throw new GatewayException($e->getMessage(), $e->getCode());
        }

        $res['order_no'] = $order_no;
        $this->success('请求成功', $res);
    }

    /**
     * 支付查询
     */
    public function notify(Wechat $wechat)
    {
        $order_no = $this->request->post('order_no');
        if (empty($order_no)) {
            $this->error('订单号不能为空');
        }
        $order = RechargeOrder::where('order_no', $order_no)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->status == 1) {
            $this->success('支付成功');
        }
        $recharge = Recharges::find($order->recharge_id);
        if (!$recharge) {
            $this->error('充值套餐不存在');
        }
        $user = Users::find($order->user_id);
        if (!$user) {
            $this->error('用户不存在');
        }
        //查询支付结果
        $res = $wechat->find($order_no);
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            if ($res['trade_state'] === 'SUCCESS') {
                $this->paySuccess($order, $user);
            } else {
                $this->error($res['trade_state_desc'], [], $res['trade_state']);
            }
        } else {
            $this->error('支付失败，请联系管理员');
        }
    }

    /**
     * 支付结果通知
     */
    public function paymentResult(Wechat $wechat)
    {
        $res = $wechat->verify();
        Log::record($res);
        if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
            $order = OrderVip::where('order_no', $res['out_trade_no'])->find();
            if ($order) {
                $user = Users::find($order->user_id);
                if ($user) {
                    $this->paySuccess($order, $user);
                }
            }
        }
        $wechat->wechatPay()->success()->send();
    }

    private function paySuccess($order, $user)
    {
        Db::startTrans();
        try {
            //更新订单状态
            $order->status = 1;
            $order->save();
            //赠送优惠券
            if ($order->present_coupon_id) {
                $coupon = Coupons::find($order->present_coupon_id);
                if ($coupon) {
                    UserCoupons::createUserCoupon($order->user_id, $coupon, true);
                }
            }
            //更新用户信息
            $money = $order->total_amount + $order->present_amount;
            $user->money += $money;
            $user->recharge_money += $order->total_amount;

            //是否满足累积升级
            $amass_upgrade = UserVip::getByAmassUpgrade($user->recharge_money);
            if ($amass_upgrade) {
                UserGrade::add($user->id, $user->vip, $amass_upgrade->name, 2);
                $user->vip = $amass_upgrade->name;
            }
            $user->save();

            //记录余额变化
            UserBalanceLog::add($user->id, $money, $order->order_no, 1);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->error('充值失败，请联系管理员') : $this->success('充值成功');
    }

    /**
     * 充值套餐
     */
    public function index()
    {
        $recharges = Recharges::where('online', 'yes')->select();
        $money = Users::getMoneyValue($this->auth->getUserId());
        $recharges ? $this->success('请求成功', ['recharges' => $recharges, 'money' => $money]) : $this->error('没有数据', [], 2);
    }

    /**
     * 充值记录
     */
    public function record()
    {
        $length = $this->request->get('length');
        $recharges = RechargeOrder::getByUserId($this->auth->getUserId(), $length);
        $recharges->items() ? $this->success('请求成功', ['recharges' => $recharges->items()]) : $this->error('没有数据', [], 2);
    }




}
